import axios from 'axios';
import { Message, MessageBox } from 'element-ui';
import store from '../store';
// import router from '../router';

axios.defaults.withCredentials = true

// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API,
  timeout: 0,
  withCredentials: true
});

// request拦截器
service.interceptors.request.use(config => {
  // Do something before request is sent
  config.withCredentials = true
  return config;
}, error => {
  // Do something with request error
  console.log(error); // for debug
  Promise.reject(error);
})

// respone拦截器
service.interceptors.response.use(
  response => {
    /**
    * 下面的注释为通过response自定义code来标示请求状态，当code返回如下情况为权限有问题，登出并返回到登录页
    * 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中
    */
    const res = response.data;
    if (res.code === -1) {
      return Promise.reject(res);
    } else if (res.code === 2) {
      const text = store.getters.uid ? '登录过期，请先登录' : '您还未登录，请登录' // 本地有uid情况是登录过期
      MessageBox.alert(text, '提示', {
        confirmButtonText: '确定',
        type: 'warning'
      }).then(() => {
        store.dispatch('LogOut').then(() => {
          location.reload() // 为了重新实例化vue-router对象 避免bug
        })
      })
      return Promise.reject(res);
    } else {
      return res;
    }
  },
  error => {
    console.log('err: ' + error);// for debug
    Message({
      message: '服务器错误：' + error.message,
      type: 'error',
      duration: 2 * 1000
    });
    return Promise.reject(error);
  }
)

export default service;
